//
//  LoginViewController.m
//  PaiLeXiongProject
//
//  Created by 小獾科技 on 2017/8/15.
//  Copyright © 2017年 小獾科技. All rights reserved.
//

#import "LoginViewController.h"
#import "LoginBabyDataViewController.h"
#import "WXApi.h"
#import "PhoneBindViewController.h"
@interface LoginViewController ()<UITextFieldDelegate, UIScrollViewDelegate, WXApiDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self addBackItem];
    
    UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithImage:[IMAGE(@"close") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(handleBtn)];
    
    self.navigationItem.rightBarButtonItem = btn;
    
    _scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
    _scrollView.delegate = self;
    _scrollView.backgroundColor = [UIColor whiteColor];
    if(GWIDTH == 320)
    {
        _scrollView.contentSize = CGSizeMake(0, GHEIGHT + 120);
    }
    else if(GWIDTH <= 375)
    {
        _scrollView.contentSize = CGSizeMake(0, GHEIGHT + 30);
    }
    else
    {
        _scrollView.contentSize = CGSizeMake(0, GHEIGHT);
    }
    [self.view addSubview:_scrollView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapAction)];
    [self.scrollView addGestureRecognizer:tap];
    [self setaNavigation];
    [self addobServer];
}

- (void)handleBtn
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"homeChange" object:nil];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void) addobServer
{
    //使用NSNotificationCenter 监听键盘出现
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShown:)
                                                 name:UIKeyboardWillChangeFrameNotification object:nil];
    //使用NSNotificationCenter 鍵盤隐藏時
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}

- (void)handleTapAction
{
    [self.view endEditing:YES];
}

/**
 * 界面布局
 */
- (void)setaNavigation
{
    //界面的布局

    //派乐熊的image
    _anXImage = [UIImageView new];
    _anXImage.image = IMAGE(@"login_logo");
    [_scrollView addSubview:_anXImage];
    [_anXImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_scrollView).offset(76);
        make.centerX.equalTo(self.view);
        make.height.equalTo(@105);
    }];
    
    //输入手机号
    _telephoneTextField = [UITextField new];
    _telephoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _telephoneTextField.tag = 1110;
    _telephoneTextField.delegate = self;
    _telephoneTextField.textColor = ColorFrom16(0x4a4a4a);
    _telephoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    [_scrollView addSubview:_telephoneTextField];
    [_telephoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_anXImage.mas_bottom).offset(47.5);
        make.left.equalTo(self.view).offset(62.5);
        make.right.equalTo(self.view).offset(-62.5);
        make.height.equalTo(@20);
    }];
    _telephoneTextField.placeholder = @"输入手机号";
    [_telephoneTextField setValue:ColorFrom16A(0x9f9f9f, 1) forKeyPath:@"_placeholderLabel.textColor"];//通过kvc去改变占位符的字体颜色
    [_telephoneTextField setValue:PFRFONT(14) forKeyPath:@"_placeholderLabel.font"];
    
    //输入手机号 下面的横线
    _line1 = [UIView new];
    _line1.backgroundColor = ColorFrom16(0xe2e2e2);
    [_scrollView addSubview:_line1];
    [_line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_telephoneTextField.mas_bottom).offset(15);
        make.left.equalTo(self.view).offset(62.5);
        make.right.equalTo(self.view).offset(-62.5);
        make.height.equalTo(@0.5);
    }];
    
    //获取验证码
    _getIdentifyingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_getIdentifyingBtn setTitle:@"验证码" forState:0];
    [_getIdentifyingBtn setTitleColor:ColorFrom16(0xffffff) forState:0];
    _getIdentifyingBtn.titleLabel.font = PFRFONT(13);
    _getIdentifyingBtn.backgroundColor = ColorFrom16(0xf9bc4f);
    //    _getIdentifyingBtn.hidden = YES;
    _getIdentifyingBtn.layer.cornerRadius = 3;
    _getIdentifyingBtn.layer.masksToBounds = YES;
    [_getIdentifyingBtn addTarget:self action:@selector(handleIdentifyingBtn:) forControlEvents:UIControlEventTouchUpInside];
    _getIdentifyingBtn.userInteractionEnabled = YES;
    [_scrollView addSubview:_getIdentifyingBtn];
    [_getIdentifyingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_line1.mas_bottom).offset(10);
        make.right.equalTo(self.view).offset(-62.5);
        make.width.equalTo(@64);
        make.height.equalTo(@28.5);
    }];
    
    
    //输入密码 或者验证码
    _identifyingTextField = [UITextField new];
    _identifyingTextField.frame = CGRectMake(62.5, 279, GWIDTH - 188, 20);
    _identifyingTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
//    _identifyingTextField.secureTextEntry = YES;
    _identifyingTextField.delegate = self;
    _identifyingTextField.textColor = ColorFrom16(0x4a4a4a);
    _identifyingTextField.tag = 1111;
    _identifyingTextField.keyboardType = UIKeyboardTypeNumberPad;
    [_scrollView addSubview:self.identifyingTextField];
    _identifyingTextField.delegate = self;
    _identifyingTextField.placeholder = @"输入验证码";
    [_identifyingTextField setValue:ColorFrom16A(0x9f9f9f, 1) forKeyPath:@"_placeholderLabel.textColor"];//通过kvc去改变占位符的字体颜色
    [_identifyingTextField setValue:PFRFONT(14) forKeyPath:@"_placeholderLabel.font"];
    //    [_identifyingTextField mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.top.equalTo(_line1.mas_bottom).offset(15);
    //        make.left.equalTo(self.view).offset(62.5);
    //        make.right.equalTo(self.view).offset(-95.5);
    //        make.height.equalTo(@20);
    //    }];
    
    
    
    //输入密码 下面的横线
    _line2 = [UIView new];
    _line2.backgroundColor = ColorFrom16(0xe2e2e2);
    [_scrollView addSubview:_line2];
    [_line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_identifyingTextField.mas_bottom).offset(15);
        make.left.equalTo(self.view).offset(62.5);
        make.right.equalTo(self.view).offset(-62.5);
        make.height.equalTo(@0.5);
    }];
    
    
    //登录按钮
    _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    _loginBtn.titleLabel.font = PFRFONT(15);
    _loginBtn.layer.backgroundColor = ColorFrom16(0xFEDE6D).CGColor;
    _loginBtn.layer.cornerRadius = 7;
    [_loginBtn setTitleColor:ColorFrom16(0x202020) forState:0];
    [_loginBtn addTarget:self action:@selector(handleLoginBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:_loginBtn];
    [_loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_line2.mas_bottom).offset(30);
        make.left.equalTo(self.view).offset(55);
        make.right.equalTo(self.view).offset(-55);
        make.height.equalTo(@40);
    }];
    //    [_loginBtn setBackgroundImage:[GlobalTool createGradualImage:CGSizeMake(ScreenWidth - 110, 48) startColor:ColorFrom16(0xffcd37) endColor:ColorFrom16(0xff9700) startLoction:1] forState:0];
    
#pragma mark - 判断是否已经安装微信
    if ([WXApi isWXAppInstalled]) {
    
        //使用社交账号登录
        _otherLogin = [UILabel new];
        _otherLogin.text = @"使用社交账号登录";
        _otherLogin.textColor = ColorFrom16(0xbbbbbb);
        _otherLogin.font = PFRFONT(13);
        [_scrollView addSubview:_otherLogin];
        [_otherLogin mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_loginBtn.mas_bottom).offset(63.5);
            make.centerX.equalTo(self.view.mas_centerX);
            make.width.equalTo(@105);
            make.height.equalTo(@24);
        }];
        
        _line = [UIView new];
        _line.backgroundColor = ColorFrom16(0xe2e2e2);
        [_scrollView addSubview:_line];
        [_line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_loginBtn.mas_bottom).offset(74);
            make.right.equalTo(_otherLogin.mas_left).offset(-1.5);
            make.width.equalTo(@50.5);
            make.height.equalTo(@0.5);
        }];
        
        _line3 = [UIView new];
        _line3.backgroundColor = ColorFrom16(0xe2e2e2);
        [_scrollView addSubview:_line3];
        [_line3 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_loginBtn.mas_bottom).offset(74);
            make.left.equalTo(_otherLogin.mas_right).offset(1.5);
            make.width.equalTo(@50.5);
            make.height.equalTo(@0.5);
        }];
        
        //最下面的微信按钮
        _weixinBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_weixinBtn setImage:IMAGE(@"login_wechat") forState:0];
        [_weixinBtn addTarget:self action:@selector(handleWxLoginBtn:) forControlEvents:UIControlEventTouchUpInside];
        [_scrollView addSubview:_weixinBtn];
        [_weixinBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(_otherLogin.mas_bottom).offset(15);
            make.width.and.height.equalTo(@47);
        }];
    }
}

//微信登录
- (void)handleWxLoginBtn:(UIButton *)sender
{
    
    @weakobj(self);
    [[ShareView sharedInstance] loginWithWxInVC:self andCallback:^(NSDictionary *dict) {
        @strongobj(self);
        NSDictionary *dataDict = dict[@"data"];
        
        NSLog(@"微信授权成功 %@", dict);
        if([[NSString stringWithFormat:@"%@", dataDict[@"typeCode"]]  isEqualToString:@"10006"])
        {//未绑定手机号
            PhoneBindViewController *bindVC = [PhoneBindViewController new];
            bindVC.unionid = dataDict[@"unionid"];
            bindVC.openid = dataDict[@"openid"];
            bindVC.head_url = dataDict[@"headimgurl"];
            bindVC.wxname = dataDict[@"nickname"];
            bindVC.string = @"微信";
            [self.navigationController pushViewController:bindVC animated:YES];
        }
        else
        {
            [GW_Tool saveLoginInfoWithDict:dict[@"data"]];
            [self loginSuccessAndCloseVC];
        }
        [SVProgressHUD dismiss];
    }];
}


/**
 * 点击登录按钮响应方法
 */
- (void)handleLoginBtn:(UIButton *)sender
{
    if(![_telephoneTextField.text isPhoneNumber])
    {
        MESSAGE_TOAST(@"请输入正确的手机号");
        return ;
    }
    if(_identifyingTextField.text.length == 0)
    {
        MESSAGE_TOAST(@"请输入验证码");
        return ;
    }
    NSDictionary *param = @{
                            @"phone"     : _telephoneTextField.text,
                            @"captcha"      : _identifyingTextField.text//暂时测试 1234
                            };
    @weakobj(self);
    [NetWork sendGetRequestURL:[NSString stringWithFormat:@"%@/passport/login?phone=%@&captcha=%@", GW_Domain, _telephoneTextField.text, _identifyingTextField.text] parameters:param completionBlockWithSuccess:^(NSDictionary *resultDict) {
        NSLog(@"登录 %@", resultDict);
        @strongobj(self);
        NSDictionary *dic = resultDict[@"data"];
        NSString *str = [NSString stringWithFormat:@"%@", dic[@"type"]];
        [[NSUserDefaults standardUserDefaults] synchronize];
        if([str isEqualToString:@"0"])//跳转到宝宝信息页
        {
            [GW_Tool saveLoginInfoWithDict:dic];
            LoginBabyDataViewController *babyVC = [LoginBabyDataViewController new];
            babyVC.loginSuccessBlock = _loginSuccessBlock;
            babyVC.closeLoginVCBlock = _closeLoginVCBlock;
            [self.navigationController pushViewController:babyVC animated:YES];
        }
        else if([str isEqualToString:@"1"])
        {
            [GW_Tool saveLoginInfoWithDict:dic];
            [self loginSuccessAndCloseVC];
        }
     
    } andFailure:^(NSError *error, NSString *errorMsg) {
        MESSAGE_TOAST(errorMsg);
        NSLog(@"%@", error);
    }];
    
}

//获取验证码按钮响应方法
- (void)handleIdentifyingBtn:(UIButton *)sender
{
    
    if(![_telephoneTextField.text isPhoneNumber])
    {
        MESSAGE_TOAST(@"请输入正确的手机号");
        return ;
    }
    [GW_Tool getIdentifying:self.getIdentifyingBtn];//倒计时
    BaseNetwork *network = [[BaseNetwork alloc] init];
    
    NSDictionary *param = @{@"phone": _telephoneTextField.text};

    [network sendPostRequestURL:[NSString stringWithFormat:@"%@/common/getcode", GW_Domain] parameters:param completionBlockWithSuccess:^(NSDictionary *resultDict) {
        NSLog(@"获取验证码 %@", resultDict);
    } andFailure:^(NSError *error, NSString *errorMsg) {
        NSLog(@"%@", error);
    }];
    
}

- (void)loginSuccessAndCloseVC {
    
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        if (self.loginSuccessBlock) {
            self.loginSuccessBlock();
        }
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //隐藏导航栏下面的黑线
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}

//键盘弹出
- (void)keyboardWillShown:(NSNotification*)aNotification
{
    NSDictionary *info = [aNotification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    //    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    //    CGSize keyboardSize = [value CGRectValue].size;
    
    //输入框位置动画加载
    [UIView animateWithDuration:duration animations:^{
        //do something
    }];
    
    NSTimeInterval animationDuration=0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    //上移55个单位，按实际情况设置
    CGRect rect=CGRectMake(0.0f, -55, GWIDTH, GHEIGHT);
    _scrollView.frame = rect;
    [UIView commitAnimations];
    
}
//键盘隐藏
- (void)keyboardWillBeHidden:(NSNotification *)aNotification
{
    NSTimeInterval animationDuration=0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    //如果当前View是父视图，则Y为20个像素高度，如果当前View为其他View的子视图，则动态调节Y的高度
    //    float Y = 20.0f;
    CGRect rect=CGRectMake(0.0f,0,GWIDTH,GHEIGHT);
    _scrollView.frame = rect;
    [UIView commitAnimations];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if(textField.tag == 1110)
    {
        _line1.backgroundColor = ColorFrom16(0xf9bc4f);
        _line2.backgroundColor = ColorFrom16(0xe2e2e2);
    }
    else if(textField.tag == 1111)
    {
        _line2.backgroundColor = ColorFrom16(0xf9bc4f);
        _line1.backgroundColor = ColorFrom16(0xe2e2e2);
    }
    
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if(textField.tag == 1110)
    {
        _line1.backgroundColor = ColorFrom16(0xe2e2e2);
    }
    else if(textField.tag == 1111)
    {
        _line2.backgroundColor = ColorFrom16(0xe2e2e2);
    }
}

//点击return收回键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.scrollView endEditing:YES];
    return YES;
}

#pragma mark - 处理通知事件
- (void)handleNotification
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)dealloc
{
    if (self.closeLoginVCBlock) {
        self.closeLoginVCBlock();
    }
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
